<?php

class Client {

    public $apiRoot = "https://openapi.akulaku.com/vendorshop/openapi/service";
//    public $apiRoot = 'http://47.244.255.10:9090/vendorshop/openapi/service'; // 测试
    public $partnerId;
    public $appKey;
    public $appSecret;
    public $connectTimeout = 5;
    public $readTimeout = 10;
    
    public $debugMode = false;

    /**
     * curl 请求
     * @param type $url
     * @param type $postFields
     * @param type $httpHeaders
     * @return type
     * @throws Exception
     */
    private function _curl($url, $postFields = null, $httpHeaders = null) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($this->readTimeout) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
        }
        if ($this->connectTimeout) {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
        }
        //https request
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        // body
        if (is_array($postFields) && 0 < count($postFields)) {
            $postBodyString = http_build_query($postFields);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postBodyString);
        }
        
        // header
        if (is_array($httpHeaders) && 0 < count($httpHeaders)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
        }
        
        $response = curl_exec($ch);

        // debug info start //
        if ($this->debugMode) {
            echo '----- curl call -----', PHP_EOL;
            echo 'url: ', $url, PHP_EOL;
            if (!empty($postBodyString)) {
                echo 'body: ', $postBodyString, PHP_EOL;
            }
            if (!empty($httpHeaders)) {
                echo 'header: ', "\n  ", implode("\n  ", $httpHeaders), PHP_EOL;
            }
            echo 'response: ', $response, PHP_EOL, PHP_EOL;
        }
        // debug info end //

        if (curl_errno($ch)) {
            throw new Exception(curl_error($ch), 0);
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                throw new Exception($response, $httpStatusCode);
            }
        }
        curl_close($ch);
        return $response;
    }

    /**
     * 调用接口
     * @param type $api
     * @param type $param
     * @param type $httpMethod
     * @param type $maxRetry
     * @return type
     */
    public function call($api, $param = [], $httpMethod, $maxRetry = 1) {
        
        $param['partnerId'] = $this->partnerId;
        $param['appKey'] = $this->appKey;
        
        // 计算签名
        $signParam = $param;
        ksort($signParam);
        $parts = [];
        foreach ($signParam as $k => $v) {
            $parts[] = "{$k}={$v}";
        }
        $signString = implode('&', $parts).$this->appSecret;
        if ($this->debugMode) {
            echo "sign string: ", $signString, PHP_EOL;
        }
        $sign = md5($signString);
        
        // 通用参数
        $header = array();
        $header[] = "methodId: $api";
        $header[] = 'timestamp: '.date('Y-m-d H:i:s', time() + 3600);
        $header[] = 'signature: '.$sign;
        if ($httpMethod === 'POST') {
            $header[] = 'Content-Type: application/xwww-formurlencoded';
        }
        
        try {
            // hack
            $requestUrl = $this->apiRoot;
            if ($httpMethod === 'GET') {
                $requestUrl = $this->apiRoot.'?'.http_build_query($param);
                $param = null;
            }
            $resp = $this->_curl($requestUrl, $param, $header);
            return $resp;
        } catch (Exception $e) {
            
            // 无授权
            if ($e->getCode() === 401 && $maxRetry > 0) {
                $maxRetry--;
                return $this->call($api, $param, $httpMethod, $maxRetry);
            }

            throw new Exception('call api failed:' . $e->getMessage());
        }
    }
}